package com.wisezone.studentmanger.listener;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.wisezone.studentmanger.model.UserMessage;
import com.wisezone.studentmanger.util.Utils;

@WebListener
public class UserServletRequestListener implements ServletRequestListener {
	public DateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	public List<UserMessage> userLists = new ArrayList<>(); // 存储所有在线用户信息

	public void requestDestroyed(ServletRequestEvent arg0) {

	}

	public void requestInitialized(ServletRequestEvent sevletRequestEvent) {
		/*
		 * ServletContext > HttpSession > ServletRequest
		 * 
		 */
		HttpServletRequest request = (HttpServletRequest) sevletRequestEvent.getServletRequest();
		HttpSession session = request.getSession();
		ServletContext servletContext = session.getServletContext();

		String sessionId = session.getId();
		UserMessage user = Utils.getUserMessageByList(userLists,sessionId);
		if(user == null){
			String ip = request.getRemoteAddr();
			String createTime = dataFormat.format(new Date());
			user = new UserMessage(sessionId, createTime, ip);
			userLists.add(user);
		}

		servletContext.setAttribute("USER_LISTS", userLists);

	}

	

}
